#include "common.h"

class Solution
{
public:
    std::vector<std::vector<int>> threeSum(std::vector<int> &nums)
    {
        std::vector<std::vector<int>> ret;
        sort(nums.begin(), nums.end(), [](int x, int y)
             { return x < y; });
        int sz = nums.size();
        for (int i = 0; i < sz - 2; ++i)
        {
            if (nums[i] > 0)
                return ret;
            if (i >= 1 && nums[i] == nums[i - 1])
            {
                continue;
            }
            int left = i + 1, right = sz - 1;
            while (left < right)
            {
                if (nums[right] + nums[left] + nums[i] == 0)
                {
                    ret.push_back({nums[i], nums[left], nums[right]});
                    // ret.push_back({nums[right],nums[left],nums[i]});
                    while (left + 1 < right && nums[left + 1] == nums[left])
                    {
                        ++left;
                    }
                    while (right - 1 > left && nums[right - 1] == nums[right])
                    {
                        --right;
                    }
                    ++left;
                    --right;
                }
                else if (nums[right] + nums[left] + nums[i] > 0)
                {
                    --right; // 这里就没必要去重了,反正要是找不到一直会--
                }
                else
                {
                    ++left;
                }
            }
        }
        return ret;
    }
};




class Solution
{
public:
    vector<vector<int>> threeSum(vector<int> &nums)
    {
        int sz = nums.size();
        if (sz < 3)
            return {{}};

        // sort
        sort(nums.begin(), nums.end(),
             [](int x, int y)
             {
                 return x < y;
             });

        vector<vector<int>> ret;
        for (int i = 0; i < sz - 2; i++)
        {
            // 优化
            if(nums[i] > 0) return ret;
            // 去重处理
            if (i > 0 && nums[i] == nums[i - 1])
            {
                continue;
            }
            int left = i + 1, right = sz - 1;
            while (left < right)
            {
                if (nums[left] + nums[right] + nums[i] == 0)
                {
                    ret.push_back({nums[i], nums[left], nums[right]});
                    while (left + 1 < right && nums[left + 1] == nums[left])
                    {
                        ++left;
                    }
                    while (right - 1 > left && nums[right - 1] == nums[right])
                    {
                        --right;
                    }
                    ++left;
                    --right;
                }
                else if (nums[left] + nums[right] + nums[i] > 0)
                {
                    right--;
                }
                else
                {
                    left++;
                }
            }
        }
        return ret;
    }
};